<template>
	<!-- <watermark> -->
		<scroll-view>
			<view style="padding: 1rem;">
				<i style="font-size: larger;color: darkblue;">动火作业审批</i>
				<view class="item-title">
					<view>动火内容(详细)<i>*</i></view>
				</view>
				<textarea auto-height placeholder="点击输入动火详情描述" style="width: 100%;min-height: 4rem;padding: 0.6rem;"
					class="item-content-select" v-model="info.taskContent">
				</textarea>
				<view class="item-title">
					<view>动火级别<i>*</i></view>
					<input class="item-content-select" disabled @click="clickSelectLeve" v-model="leveStr"
						placeholder="点击选择" />
				</view>

				<view class="item-title">
					<view>动火方式<i>*</i></view>
					<view class="content-select" @click="clickSelectMethod">
						<view class="v-select-user" v-if="info.hotWorkModeList.length>0">
							<view class="v-user-delete" v-for="(item, index) in info.hotWorkModeList" :key="index">
								<view>{{item.text}}</view>
								<view class="v-delete iconfont icon-shanchu"
									@click.stop="deletehotWorkModeList(index)"></view>
							</view>
						</view>
						<view v-else> 请选择</view>
						<view class="v-right iconfont icon-jiantou"></view>
					</view>
				</view>

				<view class="item-title">
					<view>周围危险性描述<i>*</i></view>
				</view>
				<textarea auto-height placeholder="请对签字风险惊醒详细的描述" style="width: 100%;min-height: 4rem;padding: 0.6rem;"
					class="item-content-select" v-model="info.riskDescribe">
				</textarea>

				<view class="item-title">
					<view>防护措施<i>*</i></view>
					<view class="content-select" @click="clickSelectProtectiveMeasures">
						<view class="v-select-user" v-if="info.protectMethodList.length>0">
							<view class="v-user-delete" v-for="(item, index) in info.protectMethodList" :key="index">
								<view>{{item.text}}</view>
								<view class="v-delete iconfont icon-shanchu"
									@click.stop="deleteProtectiveMeasures(index)"></view>
							</view>
						</view>
						<view v-else> 请选择</view>
						<view class="v-right iconfont icon-jiantou"></view>
					</view>
				</view>

				<view class="item-title">
					<view>动火地点<i>*</i></view>
					<input class="item-content-select" style="height: 2rem;" placeholder="请输入动火地点"
						v-model="info.hotWorkPlacr" />
				</view>
				<view class="item-title">
					<view>现场照片<i>*</i></view>
				</view>
				<view class="t-content-img">
					<view class="image_item" v-for="(item, index) in info.taskWorkImgList" :key="index"
						@tap="viewDetailImage(item)">
						<image :src="base + item" mode="aspectFill" class="image_item_img" />
					</view>
					<image v-show="info.taskWorkImgList.length <3" class="image_item iconfont icon-xiangji"
						style="font-size: 130rpx; " @click="chooseImage(info.taskWorkImgList)" />
				</view>
				<view class="item-title" style="align-items: center;text-align: center;">
					<uni-datetime-picker v-model="info.taskWorkDateList" type="datetimerange" rangeSeparator="至" />
					<!-- <i class="iconfont icon-jiahao add-icon" /> -->
				</view>
				<view class="item-title">
					<view>时长(小时):{{info.duration}}</view>
				</view>
				<view class="item-title">
					<view>作业单位<i>*</i></view>
					<radio-group class="my-readio-group" @change="changePlaceWorkRadio">
						<radio value="0" :checked="info.taskWorkCompany!='承包商'">本单位</radio>
						<radio value="1" :checked="info.taskWorkCompany=='承包商'">承包商</radio>
					</radio-group>
				</view>
				<view class="item-title" v-show="info.taskWorkCompany=='承包商'">
					<view>单位名称<i>*</i></view>
					<input class="item-content-select" style="height: 2rem;" placeholder="请输入单位名称"
						v-model="info.unitName" />
				</view>
				<view class="item-title">
					<view>作业人员<i>*</i></view>
				</view>
				<view style="padding: 0.5rem;border: 0.3px dashed #666;width: 100%;"
					v-for="( operator,index) in info.taskWorkUserList" :key="index">

					<view class="item-title">
						<view>姓名<i>*</i></view>
						<input class="item-content-select" style="height: 2rem;" placeholder="请输入姓名"
							v-model="operator.name" />
						<i class="iconfont icon-jiahao add-icon" v-if="index==0" @click="addOperatorClick" />
						<i v-else class="iconfont icon-shanchu add-icon" style="background-color: red;"
							@click="deleteOperator(index)"></i>
					</view>
					<view class="item-title">作业证照片</view>
					<view class="t-content-img">
						<view class="image_item" v-for="(item, i) in  operator.imgList" :key="i"
							@tap="viewDetailImage(item)" :data-url="base + item">
							<image :src="base + item" mode="aspectFill" class="image_item_img">
							</image>
						</view>
						<image v-show="operator.imgList.length < 3" class="image_item iconfont icon-xiangji"
							style="font-size: 130rpx; " @click="chooseWorkPermitImage(operator.imgList)"></image>
					</view>
				</view>
				<view class="item-title">
					<view>班组长<i>*</i></view>
					<view class="item-content-select" @click="userSelect(100)">
						<input type="text" disabled placeholder="点击选择" v-model="info.foremanName">
					</view>
				</view>
				<view class="item-title">
					<view>监护人<i>*</i></view>
					<view class="item-content-select" @click="userSelect(101)">
						<input type="text" disabled placeholder="点击选择" v-model="info.guardianName">
					</view>
				</view>
				<view class="item-title">
					<view>作业方案</view>
					<view>
						{{info.cassImgList.length}}/3
					</view>
				</view>
				<view>文件格式:图片,word,excel,pdf</view>
				<view class="t-content-img">
					<view class="image_item" v-for="(item, index) in info.cassImgList" :key="index"
						@tap="viewDetailImage(item)">
						<image :src="base + item" mode="aspectFill" class="image_item_img" />
					</view>
					<view v-show="info.cassImgList.length <3" @click="chooseImage(info.cassImgList)"
						class="iconfont icon-jiahao"
						style="width: 4rem;height: 4rem;border: 0.4px dotted #666;display: flex;align-items: center;justify-content: center;">
					</view>
				</view>
				<view class="item-title">
					<view>是否需要气体检测</view>
					<radio-group class="my-readio-group" @change="doWeNeedGasDetectionChange">
						<radio value="0" :checked="info.detector =='是'">是</radio>
						<radio value="1" :checked="info.detector !='是'">否</radio>
					</radio-group>
				</view>
				<view v-if="info.detector =='是'">
					<view class="item-title" style="background-color: #eee;border: 0.3px solid #666;padding: 0px 1rem;">
						<view>气体检测结果</view>
						<view class="iconfont" :class="showDetection?'icon-jiantou':'icon-yincang'"
							@click="showDetectionClick"></view>
					</view>
					<view class="item-title" v-for="(item , i) in info.hotWorkGasDetection" :key="i" v-show="item.show"
						v-if="showDetection">
						<view>{{item.name}} <i>*</i> </view>
						<view class="item-content-select" style="width: 40%;">
							<input type="text" placeholder="点击输入" v-model="item.value">
						</view>
					</view>
				</view>
				<view class="item-title" style="background-color: #eee;border: 0.3px solid #666;padding: 0px 1rem;">
					<view>检查表</view>
					<view class="iconfont" :class="showTbale?'icon-jiantou':'icon-yincang'" @click="showTableListClick">
					</view>
				</view>
				<lxsh-table :columns="tableColums" :tableList="info.contentDetailQOList" v-show="showTbale"
					:showOperate='false' :radioConfig="contentDetailRadio" @updateTableList="updateTableList">
				</lxsh-table>

				<view class="item-title">
					<view>其他安全措施</view>
				</view>
				<textarea auto-height placeholder="请输入其他安全措施" style="width: 100%;min-height: 4rem;padding: 0.6rem;"
					class="item-content-select" v-model="info.otherStep">
				</textarea>
				<view class="item-title">
					<view>抄送人</view>
					<view class="item-content-select" @click="userSelect(102)">
						<input type="text" disabled placeholder="点击选择" v-model="info.makePersionName">
					</view>
				</view>
				<view style="height: 1px; border-bottom: 0.5px solid #666;margin: 1rem 0px;"></view>
				<i style="font-size: larger;display: flex;color: darkblue;">
					审批流程
					<i style="color: #666;font-size: small;display: flex;align-items: flex-end;"> (可在后台自定义各级审批人名称)</i>
				</i>
				<view class="item-title" v-for="(item , index ) in info.psmApprovalsetVOList" :key="index">
					<view>{{item.approvalUser}}<i>*</i></view>
					<view class="item-content-select" @click="userSelect(index)">
						<input type="text" disabled placeholder="点击选择" v-model="item.approvalUserName">
					</view>
				</view>
				<view class="item-title">
					<view>完工后确认人<i v-show="isMust==1">*</i></view>
					<view class="item-content-select" @click="userSelect(103)">
						<input type="text" disabled placeholder="点击选择" v-model="info.confirmUserName">
					</view>
				</view>
				<view class="item-title" style="margin-top: 4rem;">
					<button type="warn" style="background-color: #3399ff;" @click="saveDraftsClick">存草稿</button>
					<button type="primary" @click="doAddHotWork">提交</button>
					<button type="default">返回</button>
				</view>
			</view>
		</scroll-view>
	<!-- </watermark> -->
</template>

<script>
	import commonConstants from "@/common/constants/commonConstants.js"
	import hotWorkApi from "@/pages_psm/api/permit-to-work/hot_work.js"
	import lxshTable from "@/pages_psm/components/lxsh-table.vue"
	import {
		encrypt,
		decrypt
	} from '@/common/js/des.js'
	export default {
		components: {
			lxshTable
		},
		data() {
			return {
				base: commonConstants.request.imageUrl,
				info: {
					taskContent: '', //动火内容
					hotWorkLevel: -1, //动火级别
					hotWorkMode: '', //动火方式
					hotWorkModeList: [], //动火方式 前端
					riskDescribe: '', //周围危险性描述
					protectMethod: '', //防护措施
					protectMethodList: [], //防护措施 前段
					taskWorkImg: '', //现场照片
					taskWorkImgList: [], //现场照片 前端
					taskWorkDate: '', //日期
					taskWorkDateList: [this.getDateTime(Date.now()), this.getDateTime(Date.now() + 1 * 2 *
						3600000)], //日期  前端
					duration: '', //时长
					taskWorkCompany: '本单位',
					unitName: "寰宇东方国际集装箱(青岛)有限公司",
					taskWorkUserList: [{
						name: '',
						imgList: []
					}], //作业人员  前端
					foremanCode: '', //班长编码
					foremanName: '', //班长名称
					guardianCode: '', //监护人编码
					guardianName: '', //监护人名称
					cassImg: '', //作业方案
					cassImgList: [], //作业方案  前端
					detector: '否', //是否气体检测
					detectorResult: '', //气体检测结果
					hotWorkGasDetection: hotWorkApi.HOT_WORK_GAS_DETECTION, //气体检测结果 前端
					contentDetailQOList: [{
						contentDescribe: "焊接人员必须持熔化焊接与热切割作业上岗，无证人员禁止从事焊接作业 ",
						isStatus: "-1"
					}, {
						contentDescribe: "作业前清除动火现场及周围的可燃物，配备满足现场应急需求的消防器材",
						isStatus: "-1"
					}, {
						contentDescribe: "动火点10米范围内及动火点下方不应同时进行可燃溶剂清洗或喷漆等其他产生易燃易爆气、液体的作业",
						isStatus: "-1"
					}, {
						contentDescribe: "使用气割、气焊动火作业时，乙炔 (丙烷)瓶应直立放置，氧气牌与乙炔 (丙烷)间距不应小于5米，二者与作业地点间距不应小于10米，并应设置防晒、防倾倒措施",
						isStatus: "-1"
					}], //检查表(从检查设置表取的)
					otherStep: '', //其他安全措施
					makePersionName: '', //抄送人
					makePersionCode: '',
					secureUserCode: '', //安全员
					secureUserName: '',
					psmApprovalsetVOList: [], //审核人列表
					confirmUserCode: '', //完工确认人
					confirmUserName: '', //完工确认人
					signImgName: '', //提交人签名
					hotWorkPlacr: '' //动火地点
				},

				showTbale: true,
				showDetection: true,


				contentDetailRadio: [{
					name: '是',
					value: '0'
				}, {
					name: "不适用",
					value: '1'
				}],
				tableColums: [{
					key: 'contentDescribe',
					value: '安全措施',
					type: 'text',
				}, {
					key: 'isStatus',
					value: '确认栏',
					type: 'radio',
					width: '6.4rem'
				}],
				isMust: 0, //完工人是否必填

			}
		},
		watch: {
			'info.taskWorkDateList': {
				handler: function(val, oldVal) {
					let str = ''
					if (val.length > 0) {
						let dur = new Date(val[1]) - new Date(val[0])
						str = Math.floor(dur / (1000 * 60 * 60))
					} else {
						str = "选择时间"
					}
					this.info.duration = str
				},
				immediate: true
			}
		},
		computed: {
			duration() {

			},
			leveStr() {
				if (this.info.hotWorkLevel < 0) {
					return ""
				} else {
					return hotWorkApi.HOT_WORK_LEVE[this.info.hotWorkLevel].text
				}
			},
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		methods: {
			/**
			 * 点击提交
			 */
			doAddHotWork() {
				uni.removeStorage({
					key: 'hot_work_add',
					success: function(res) {
						uni.showToast({
							icon: 'success',
							title: "提交成功"
						})
						setTimeout(()=>{
							uni.navigateBack()
						},2000)
					}
				});
			},
			/**
			 * 点击保存草稿箱
			 */
			saveDraftsClick() {
				this.info.hotWorkModeList.forEach((i, index) => {
					this.info.hotWorkMode = this.info.hotWorkMode + i.text + ((index + 1) == this.info
						.hotWorkModeList.length ? '' : ',')
				})
				
				
				this.info.protectMethodList.forEach((i, index) => {
					this.info.protectMethod = this.info.protectMethod + i.text + ((index + 1) == this.info
						.protectMethodList.length ? '' : ',')
				})
				
				
				this.info.taskWorkImgList.forEach((i, index) => {
					this.info.taskWorkImg = this.info.taskWorkImg + i + ((index + 1) == this.info
						.taskWorkImgList.length ? '' : ',')
				})
				this.info.taskWorkDate =JSON.stringify(this.info.taskWorkDateList)
				this.info.cassImgList.forEach((i, index) => {
					this.info.cassImg = this.info.cassImg + i + ((index + 1) == this.info
						.cassImgList.length ? '' : ',')
				})
				this.info.detectorResult = JSON.stringify(this.info.hotWorkGasDetection)
				uni.setStorage({
					key: 'hot_work_add',
					data: JSON.stringify(this.info),
					success: function() {
						uni.showToast({
							icon: 'success',
							title: "保存成功"
						})
					}
				});
			},
			/**
			 * 更新表格数据
			 * @param {Object} item
			 */
			updateTableList(item) {
				this.info.contentDetailQOList[item.index][item.key] = item.item[item.key]
			},
			/**
			 * 删除 动火方式
			 */
			deletehotWorkModeList(index) {
				this.info.hotWorkModeList.splice(index, 1)
			},
			/**
			 * 删除 防护措施
			 * @param {Object} index
			 */
			deleteProtectiveMeasures(index) {
				this.info.protectMethodList.splice(index, 1)
			},
			doWeNeedGasDetectionChange(e) {
				if (e.detail.value == 0) {
					this.info.detector = '是'
				} else if (e.detail.value == 1) {
					this.info.detector = '否'
				}
			},
			/**
			 * 控制显示隐藏 检测
			 */
			showDetectionClick() {
				this.showDetection = !this.showDetection
			},
			showTableListClick() {
				this.showTbale = !this.showTbale
			},
			/**
			 * 选择人员

			 * @param {Object} type
			 */
			userSelect(type) {
				var that = this;
				uni.navigateTo({
					url: '/pages/general/select-manager/select-manager',
					events: {
						// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
						getSelectManager: function(data) {
							console.log(data.data.userCode, data.data.userName);
							if (type == 100) {
								//班组长
								that.info.foremanCode = data.data.userCode
								that.info.foremanName = data.data.userName
							} else if (type == 101) {
								//监护人
								that.info.guardianCode = data.data.userCode
								that.info.guardianName = data.data.userName
							} else if (type == 102) {
								//抄送人
								that.info.makePersionCode = data.data.userCode
								that.info.makePersionName = data.data.userName
							} else if (type == 103) {
								//完工确认人
								that.info.confirmUserCode = data.data.userCode
								that.info.confirmUserName = data.data.userName
							} else {
								//审批流
								that.info.psmApprovalsetVOList[type].approvalUserName = data.data.userName
								that.info.psmApprovalsetVOList[type].approvalUserCode = data.data.userCode
							}
						}
					},
				})
			},
			getDateTime(date, addZero = true) {
				return `${this.getDate(date, addZero)} ${this.getTime(date, addZero)}`
			},
			getDate(date, addZero = true) {
				date = new Date(date)
				const year = date.getFullYear()
				const month = date.getMonth() + 1
				const day = date.getDate()
				return `${year}-${addZero ? this.addZero(month) : month}-${addZero ? this.addZero(day) : day}`
			},
			getTime(date, addZero = true) {
				date = new Date(date)
				const hour = date.getHours()
				const minute = date.getMinutes()
				const second = date.getSeconds()
				return this.hideSecond ?
					`${addZero ? this.addZero(hour) : hour}:${addZero ? this.addZero(minute) : minute}` :
					`${addZero ? this.addZero(hour) : hour}:${addZero ? this.addZero(minute) : minute}:${addZero ? this.addZero(second) : second}`
			},
			addZero(num) {
				if (num < 10) {
					num = `0${num}`
				}
				return num
			},
			/**
			 * 删除作业人员
			 * @param {Object} index
			 */
			deleteOperator(index) {
				this.info.taskWorkUserList.splice(index, 1)
			},
			/**
			 * 点击新增作业人员
			 */
			addOperatorClick() {
				this.info.taskWorkUserList.push({
					name: '',
					imgList: []
				})
			},
			/**
			 * 选择人员作业证照片
			 */
			chooseWorkPermitImage(imgList) {
				this.chooseImage(imgList)
			},
			// 选择现场图片
			chooseImage(imgList) {
				uni.chooseImage({
					count: 3, //一次可以选择的数量
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'], //从手机选择
					success: res => {
						console.log(res);
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							console.log(res.tempFilePaths[i])
							this.uploadImage(res.tempFilePaths, i, imgList)
						}
					}
				})
			},
			// 上传图片
			uploadImage(tempFilePaths, index, imgList) {
				let that = this
				uni.uploadFile({
					url: commonConstants.request.resourceUrl + commonConstants.request.context.path.system +
						'/uploadFile/ems', //仅为示例，非真实的接口地址
					filePath: tempFilePaths[index],
					name: 'file',
					header: {
						Authorization: decrypt(uni.getStorageSync('token'), 3)
					},
					formData: {
						user: 'test'
					},
					success: res => {
						//对于返回数据的处理，根据实际情况调整
						let data = JSON.parse(res.data)
						if (data.success) {
							if (imgList) {
								imgList.push(data.list[0])
							}
						} else {
							uni.showToast({
								title: "图片上传失败",
								icon: 'none'
							})
						}
					}
				})
			},
			viewDetailImage(item, e) {
				console.log(item, e);
				uni.previewImage({
					urls: [this.base + item]
				});
			},
			changePlaceWorkRadio(event) {
				if (event.detail.value == 0) {
					this.info.taskWorkCompany = "本单位"
					this.info.unitName = "寰宇东方国际集装箱(青岛)有限公司";
				} else {
					this.info.taskWorkCompany = "承包商"
					this.info.unitName = "";
				}
			},
			/**
			 * 选择防护措施
			 */
			clickSelectProtectiveMeasures(e) {
				let that = this
				// this.protectiveMeasuresIndex = e.detail.value
				this.navigateToSelectMultiple({
					url: commonConstants.request.context.path.auth +
						'/basedata/dictionary/getDictionaryComboByParentDictionaryCode',
					param: {
						parentDictionaryCode: "HOT_WORK_PROTECT"
					},
					forPager: false,
					oldData: that.info.protectMethodList
				}, (list) => {
					that.info.protectMethodList.length = 0
					list.forEach((item) => {
						that.info.protectMethodList.push(item)
					})
				})
			},
			/**
			 * 选择动火方式
			 */
			clickSelectMethod(e) {
				let that = this
				this.navigateToSelectMultiple({
					url: commonConstants.request.context.path.auth +
						'/basedata/dictionary/getDictionaryComboByParentDictionaryCode',
					param: {
						parentDictionaryCode: "HOT_WORK_METHOD"
					},
					forPager: false,
					oldData: that.info.hotWorkModeList
				}, (list) => {
					console.log(list, "=====>>>>");
					that.info.hotWorkModeList.length = 0
					list.forEach((item) => {
						that.info.hotWorkModeList.push(item)
					})
				})
			},
			navigateToSelectMultiple(data, collback) {
				uni.navigateTo({
					url: '/pages_psm/model/public/lxsh-select-multiple',
					success: (res) => {
						console.log("发送消息");
						uni.$emit('requestData', JSON.stringify(data))
					},
					events: {
						getSelect: function(data) {
							if (collback) {
								collback(data.list)
							}
						}
					},
				})
			},
			/**
			 * 选择动火级别
			 */
			clickSelectLeve() {
				let that = this
				let list = []
				hotWorkApi.HOT_WORK_LEVE.forEach((item) => {
					list.push(item.text)
				})
				uni.showActionSheet({
					itemList: list,
					success: function(res) {
						that.info.hotWorkLevel = hotWorkApi.HOT_WORK_LEVE[res.tapIndex].value
						hotWorkApi.getTaskSetUserNameList({
							taskLevelCode: hotWorkApi.HOT_WORK_LEVE[res.tapIndex].value,
							taskType: 0
						}, (reset) => {
							that.isMust = reset.data?.isMust
							reset.data.psmApprovalsetVOList?.forEach((item) => {
								item.approvalUserName = ''
								that.info.psmApprovalsetVOList.push(item)
							})
						})
						//测试代码
						let list = [{
								"approvalUser": "作业部门班组长"
							},
							{
								"approvalUser": "作业部门经理"
							},
							{
								"approvalUser": "安环部经办人"
							}
						]
						that.info.psmApprovalsetVOList.length = 0
						list.forEach(i => {
							i.approvalUserName = ''
							i.approvalUserCode = ''
							that.info.psmApprovalsetVOList.push(i)
						})
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},
			/**
			 * 页面初始话 获取基础数据
			 */
			requesetInfo() {

			}
		},
		onLoad() {
			console.log("onLoad");
			this.requesetInfo()
			let that = this
			uni.getStorage({
				key: 'hot_work_add',
				success: function(res) {
					console.log(res.data, "获取到的缓存值");
					if (res.data) {
						that.info = JSON.parse(res.data)
					}
				}
			});
		}
	}
</script>

<style>
	@import url("/pages_psm/model/permit-to-work/common-style.css");

	
</style>